<?php
/**
 * @package		简易CMS
 * @subpackage	功能：会员相关处理
 * @version		$Id: option_member.php 8 2012-06-07 12:37:35Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2009 - 2010 Hoping Software Studio. All rights reserved.
 */


if (!defined('IN_JYCMS')) {
	exit('Access Denied');
}
define('NOROBOT', TRUE);
define('CURSCRIPT', 'member');

class member_ctrl extends application {

	function __construct() {
		$this->member_ctrl();
	}

	function member_ctrl() {
		$this->allowaction = array(
			'login', 'logout', 'clearcookies', 'register', 'usergroup', 'notice', 'profile', 'lostpasswd', 'getpasswd', 'credit'
		);
		$this->cachelist = array(
			'usergroups', 'modreasons'
		);
		parent::__construct();
		$task = $_G['gp_task'];
		if($task == 'register' && $mainframe->var['task'] != $_G['setting']['regname']) {
			showmessage('undefined_action');
		}
		$needlogin = array('update', 'usergroup', 'notice', 'credit');
		if(in_array($task, $needlogin) &&!$_G['uid']){
			showmessage('to_login', '', array(), array('showmsg' => true, 'login' => 1));
		}

	}

	/**
	 * 积分相关处理
	 *
	 * @global array $_G
	 */
	function onCredit(){
		global $_G;
		$perpage = 20;
		$page = empty($_GET['page']) ? 1 : intval($_GET['page']);
		if($page < 1) $page = 1;
		$start = ($page-1) * $perpage;
		ckstart($start, $perpage);
		checkusergroup();
		$operation = in_array($_GET['op'], array('base', 'log', 'rule')) ? trim($_GET['op']) : 'base';
		$_GET['op'] = $_G['gp_op'] = $operation;
		$opactives = array($operation =>' class="a"');
		if($operation == 'base') {
			$_CACHE['creditsettings'] = array();
			$navtitle = lang('core', 'Credit');
			$tpl = 'member/credit_base';
		} elseif ($operation == 'rule'){
			$wheresql = '';
			$list = array();
			$rid = intval($_G['gp_rid']);
			if($rid) {
				$wheresql = " WHERE rid='$rid'";
			}
			$query = DB::query("SELECT * FROM #__common_credit_rule $wheresql ORDER BY rid ASC");
			while($value = DB::fetch($query)) {
				$list[$value['action']] = $value;
			}
			$_TPL['cycletype'] = array(
							'0' => lang('', 'One time'),
							'1' => lang('', 'Everyday'),
							'2' => lang('', 'Hourly'),
							'3' => lang('', 'Interval minutes'),
							'4' => lang('', 'Open-cycle')
						);
			$tpl = 'member/credit_base';
		} elseif ($operation == 'log') {
			$page = empty($_GET['page'])?1:intval($_GET['page']);
			if($page<1) $page=1;
			$perpage = 20;
			$start = ($page-1)*$perpage;

			$theurl = 'index.php?option=member&task=creditlog';
			$multi = '';
				$count = DB::result(DB::query("SELECT count(*) FROM #__common_credit_rule_log WHERE uid='$_G[uid]'"), 0);
				if($count) {
					$query = DB::query("SELECT r.rulename, l.* FROM #__common_credit_rule_log l LEFT JOIN #__common_credit_rule r USING(rid) WHERE l.uid='$_G[uid]' ORDER BY l.dateline DESC LIMIT $start,$perpage");
					while($value = DB::fetch($query)) {
						$list[] = $value;
					}
				}

			if($count) {
				$multi = multi($count, $perpage, $page, $theurl);
			}
			$tpl = 'member/credit_log';
		}
		include template($tpl);
	}

	/**
	 * 获取密码
	 *
	 * @global array $_G
	 */
	function onGetPassWD(){
		global $_G;
		if($_G['gp_uid'] && $_G['gp_id']) {
			$member = DB::fetch_first("SELECT m.username, m.email FROM #__common_member m
				WHERE m.uid='$_G[gp_uid]'");
			list($dateline, $operation, $idstring) = explode("\t", $member['authstr']);
			if($dateline < TIMESTAMP - 86400 * 3 || $operation != 1 || $idstring != $_G['gp_id']) {
				showmessage('You use the ID does not exist or has expired, can not retrieve your password.', NULL);
			}
			if(!submitcheck('getpwsubmit') || $_G['gp_newpasswd1'] != $_G['gp_newpasswd2']) {
				$hashid = $_G['gp_id'];
				$uid = $_G['gp_uid'];
				include template('member/getpasswd');
			} else {
				if($_G['gp_newpasswd1'] != addslashes($_G['gp_newpasswd1'])) {
					showmessage('Password empty or contains illegal characters, go back to re-fill.');
				}
				uc_user_edit($member['username'], $_G['gp_newpasswd1'], $_G['gp_newpasswd1'], $member['email'], 1, 0);
				$password = md5(random(10));
				DB::query("UPDATE #__common_member SET password='$password' WHERE uid='$_G[gp_uid]'");
				showmessage('Your password has been reset, please use the new password.', '', array(), array('login' => 1));
			}
		}
	}

	/**
	 * 密码重置
	 *
	 * @global array $_G
	 */
	function onLostPassWD(){
		global $_G;
		if(submitcheck('lostpwsubmit')) {
			list($tmp['uid'], , $tmp['email']) = uc_get_user($_G['gp_username']);
			if($_G['gp_email'] != $tmp['email']) {
				showmessage('User Name, Email address or security question does not match, please return amended.');
			}
			$member = DB::fetch_first("SELECT uid, username, adminid, email FROM #__common_member WHERE uid='$tmp[uid]'");
			if(!$member) {
				showmessage('User Name, Email address or security question does not match, please return amended.');
			} elseif($member['adminid'] == 1 || $member['adminid'] == 2) {
				showmessage('Administrators and Super Moderators can not be used to retrieve the password feature, please return.');
			}
			if($member['email'] != $tmp['email']) {
				DB::query("UPDATE #__common_member SET email='".addslashes($tmp['email'])."' WHERE uid='".addslashes($tmp['uid'])."'");
			}
			$idstring = random(6);
			require_once libfile('function/mail');
			$get_passwd_subject = lang('email', 'get_passwd_subject');
			$get_passwd_message = lang(
				'email',
				'get_passwd_message',
				array(
					'username' => $member['username'],
					'sitename' => $_G['setting']['sitename'],
					'siteurl' => $_G['siteurl'],
					'uid' => $member['uid'],
					'idstring' => $idstring,
					'clientip' => $_G['clientip'],
				)
			);
			sendmail("$_G[gp_username] <$tmp[email]>", $get_passwd_subject, $get_passwd_message);
			showmessage('Methods have been Retrieve Password Email sent to your mailbox, <br /> within 3 days please change your password.', $_G['siteurl']);
		}
	}

	/**
	 * 个人资料
	 *
	 * @global array $_G
	 */
	function onProfile() {
		global $_G;
		$uid = empty($_GET['uid']) ? $_G['uid'] : intval($_GET['uid']);

		if ($_GET['username']) {
			$member = DB::fetch_first("SELECT uid FROM #__common_member WHERE username='$_GET[username]' LIMIT 1");
			if (empty($member)) {
				showmessage('The user does not exist!');
			}
			$uid = $member['uid'];
		}

		if ($uid) {
			$space = getspace($uid);
			if (empty($space)) {
				showmessage('The user does not exist!');
			}
		}
		if (empty($space)) {
			showmessage('You must be logged in to continue browsing!', null, array(), array('showmsg' => true, 'login' => 1));
		} else {
			$navtitle = $space['username'];
			if ($space['status'] == -1 && $_G['adminid'] != 1) {
				showmessage('Space has been locked for access, if in doubt please contact the webmaster!');
			}
			if (in_array($space['groupid'], array(4, 5, 6)) && ($_G['adminid'] != 1 && $space['uid'] != $_G['uid'])) {
				$_GET['do'] = $do = 'profile';
			}

			if (!$space['self'])
				$_GET['view'] = 'me';
		}

		$diymode = 0;

		$space['admingroup'] = $_G['cache']['usergroups'][$space['adminid']];

		$space['group'] = $_G['cache']['usergroups'][$space['groupid']];

		if ($space['extgroupids']) {
			$newgroup = array();
			$e_ids = explode(',', $space['extgroupids']);
			foreach ($e_ids as $e_id) {
				$newgroup[] = $_G['usergroups'][$e_id]['grouptitle'];
			}
			$space['extgroupids'] = implode(',', $newgroup);
		}

		$space['regdate'] = dgmdate($space['regdate']);
		if ($space['lastvisit'])
			$space['lastvisit'] = dgmdate($space['lastvisit']);
		if ($space['lastactivity']) {
			$space['lastactivitydb'] = $space['lastactivity'];
			$space['lastactivity'] = dgmdate($space['lastactivity']);
		}
		if ($space['lastpost'])
			$space['lastpost'] = dgmdate($space['lastpost']);
		if ($space['lastsendmail'])
			$space['lastsendmail'] = dgmdate($space['lastsendmail']);

		if ($_G['uid'] == $space['uid'] || $_G['group']['allowviewip']) {
			require_once libfile('function/misc');
			$space['regip_loc'] = convertip($space['regip']);
			$space['lastip_loc'] = convertip($space['lastip']);
		}

		$space['timeoffset'] = empty($space['timeoffset']) ? '9999' : $space['timeoffset'];

		$upgradecredit = $space['uid'] && $space['group']['type'] == 'member' && $space['group']['creditslower'] != 999999999 ? $space['group']['creditslower'] - $space['credits'] : false;

		$navtitle = lang('space', '{who} Profile', array('who' => $space['username']));
		$metakeywords = lang('space', '{who} Profile', array('who' => $space['username']));
		$metadescription = lang('space', '{who} Profile', array('who' => $space['username']));

		if (!$_G['inajax']) {
			include_once template("member/profile");
		} else {
			include_once template("member/card");
		}
	}

	/**
	 * 通知、提醒
	 *
	 * @global array $_G
	 */
	function onNotice() {
		global $_G;
		$space = getspace($_G['uid']);
		$perpage = 100;

		$page = empty($_GET['page']) ? 0 : intval($_GET['page']);
		if ($page < 1)
			$page = 1;
		$start = ($page - 1) * $perpage;

		ckstart($start, $perpage);

		$list = array();
		$count = 0;
		$multi = '';

		$view = 'notice';
		$actives = array($view => ' class="a"');

		if (!empty($_GET['ignore'])) {
			DB::update('common_notification', array('new' => '0', 'from_num' => 0), array('new' => '1', 'uid' => $_G['uid']));

			$changecount = 0 - $space['notifications'];
			if ($changecount) {
				member_status_update($_G['uid'], array('notifications' => $changecount));
			}
		}

		$type = trim($_GET['type']);
		$typesql = $type ? "AND type='$type'" : '';

		$fuids = $newids = array();
		$count = DB::result(DB::query("SELECT COUNT(*) FROM #__common_notification WHERE uid='$_G[uid]' $typesql"), 0);
		if ($count) {
			$query = DB::query("SELECT * FROM #__common_notification WHERE uid='$_G[uid]' $typesql ORDER BY new DESC, dateline DESC LIMIT $start,$perpage");
			while ($value = DB::fetch($query)) {
				if ($value['new']) {
					$newids[] = $value['id'];
					$value['style'] = 'color:#000;font-weight:bold;';
				} else {
					$value['style'] = '';
				}
				$fuids[$value['id']] = $value['authorid'];
				if ($value['from_num'] > 0)
					$value['from_num'] = $value['from_num'] - 1;
				$list[$value['id']] = $value;
			}
			$multi = multi($count, $perpage, $page, "index.php?option=member&task=notice");
		}

		$newnotice = $space['notifications'];
		if ($newids) {
			DB::query("UPDATE #__common_notification SET new='0', from_num='0' WHERE id IN (" . dimplode($newids) . ")");
			$newcount = DB::result(DB::query("SELECT COUNT(*) FROM #__common_notification WHERE uid='$_G[uid]' AND new='1'"), 0);

			$changecount = $newcount - $space['notifications'];
			if ($changecount) {
				member_status_update($_G['uid'], array('notifications' => $changecount));
			}

			$space['notifications'] = $newcount;
		}

		$newprompt = $space['notifications'];

		if ($newprompt != $space['newprompt']) {
			$space['newprompt'] = $newprompt;
			DB::update('common_member', array('newprompt' => $newprompt), array('uid' => $_G['uid']));
		}

		dsetcookie('promptstate_' . $_G['uid'], $newprompt, 31536000);
		include_once template("member/notice");
	}

	/**
	 * 会员组
	 * @global array $_G
	 * @global array $bperms
	 */
	function onUserGroup() {
		global $_G;
		global $bperms;
		$extgroupids = $_G['member']['extgroupids'] ? explode("\t", $_G['member']['extgroupids']) : array();

		$space = getspace($_G['uid']);

		$credits = $space['credits'];
		$activeus = array();

		$language = lang('misc');
		$permlang = $language;
		unset($language);

		$maingroup = $_G['group'];
		$ptype = in_array($_G['gp_ptype'], array(0, 1, 2)) ? intval($_G['gp_ptype']) : 0;
		foreach ($_G['cache']['usergroups'] as $gid => $value) {
			$cachekey[] = 'usergroup_' . $gid;
		}
		loadcache($cachekey);
		$_G['group'] = $maingroup;
		$sidegroup = $usergroups = $activegs = array();
		$nextupgradeid = $nextexist = 0;
		if(!$groupterms['ext']) $groupterms['ext'] =array();
		$switchmaingroup = $_G['group']['grouppublic'] || isset($groupterms['ext']) ? 1 : 0;
		foreach ($_G['cache']['usergroups'] as $gid => $group) {
			$group['grouptitle'] = strip_tags($group['grouptitle']);
			if ($group['type'] == 'special') {
				$type = $_G['cache']['usergroup_' . $gid]['radminid'] ? 'admin' : 'user';
			} elseif ($group['type'] == 'system') {
				$type = $_G['cache']['usergroup_' . $gid]['radminid'] ? 'admin' : 'user';
			} elseif ($group['type'] == 'member') {
				$type = 'upgrade';
			}
			if ($nextupgradeid && $group['type'] == 'member') {
				$_G['gp_gid'] = $gid;
				$nextupgradeid = 0;
			}
			$g = '<a href="index.php?option=member&task=usergroup&gid=' . $gid . '"' . (!empty($_G['gp_gid']) && $_G['gp_gid'] == $gid ? ' class="xi1"' : '') . '>' . $group['grouptitle'] . '</a>';
			if (in_array($gid, $extgroupids)) {
				$usergroups['my'] .= $g;
			}
			$usergroups[$type] .= $g;
			if (!empty($_G['gp_gid']) && $_G['gp_gid'] == $gid) {
				$switchtype = $type;
				if (!empty($_GET['gid'])) {
					$activegs[$switchtype] = ' a';
				}
				$currentgrouptitle = $group['grouptitle'];
				$sidegroup = $_G['cache']['usergroup_' . $gid];
				if ($_G['cache']['usergroup_' . $gid]['radminid']) {
					$admingids[] = $gid;
				}
			} elseif (empty($_G['gp_gid']) && $_G['groupid'] == $gid && $group['type'] == 'member') {
				$nextupgradeid = 1;
			}
		}
		$usergroups['my'] = '<a href="index.php?option=member&task=usergroup">' . $maingroup['grouptitle'] . '</a>' . $usergroups['my'];
		if ($activegs == array()) {
			$activegs['my'] = ' a';
		}
		$bperms = array('allowvisit', 'allowsearch', 'disablepostctrl', 'allowclick', 'allowhtml', 'allowcommentarticle', 'disableperiodctrl', 'allowarticle', 'allowarticlemod', 'ignorecensor');

		$allperms = array();
		if ($sidegroup) {
			foreach ($bperms as $pkey) {
				$allperms[$pkey][$sidegroup['groupid']] = $sidegroup[$pkey];
			}
		}

		$publicgroup = array();
		$extgroupids[] = $_G['groupid'];
		$query = DB::query("SELECT * FROM #__common_usergroup WHERE (type='special' AND system<>'private' AND radminid='0') OR groupid IN (" . dimplode(array_unique($extgroupids)) . ") ORDER BY type, system");
		while ($group = DB::fetch($query)) {
			$group['allowsetmain'] = in_array($group['groupid'], $extgroupids);
			$publicgroup[$group['groupid']] = $group;
		}
		$_G['gp_perms'] = 'member';
		if ($sidegroup) {
			$group = $sidegroup;
		}

		include_once template("member/usergroup");
	}

	/**
	 * 注册
	 *
	 * @global array $_G
	 * @global <type> $groupinfo
	 */
	function onRegister() {
		global $_G, $groupinfo;
		if ($_G['setting']['siteclosed']) {
			showmessage('Sorry, the current site against a new user to register, please return.', NULL, array(), array('login' => 1));
		}

		if (!function_exists('sendmail')) {
			include libfile('function/mail');
		}
		$_G['setting']['reginput'] = unserialize($_G['setting']['reginput']);
		if (!preg_match('/^[A-z]\w+?$/', $_G['setting']['reginput']['username'])) {
			$_G['setting']['reginput']['username'] = 'username';
		}
		if (!preg_match('/^[A-z]\w+?$/', $_G['setting']['reginput']['password'])) {
			$_G['setting']['reginput']['password'] = 'password';
		}
		if (!preg_match('/^[A-z]\w+?$/', $_G['setting']['reginput']['password2'])) {
			$_G['setting']['reginput']['password2'] = 'password2';
		}
		if (!preg_match('/^[A-z]\w+?$/', $_G['setting']['reginput']['email'])) {
			$_G['setting']['reginput']['email'] = 'email';
		}

		$_G['gp_username'] = $_G['gp_' . $_G['setting']['reginput']['username']];
		$_G['gp_password'] = $_G['gp_' . $_G['setting']['reginput']['password']];
		$_G['gp_password2'] = $_G['gp_' . $_G['setting']['reginput']['password2']];
		$_G['gp_email'] = $_G['gp_' . $_G['setting']['reginput']['email']];

		if ($_G['uid']) {
			showmessage('Welcome back, {username}. Login now will be transferred to the former page.', 'index.php', array('username' => $_G['member']['username'], 'uid' => $_G['uid']));
		} elseif (!$_G['setting']['regstatus']) {
			showmessage(!$_G['setting']['regclosemessage'] ? 'Sorry, the current site against a new user to register, please return.' : str_replace(array("\r", "\n"), '', $_G['setting']['regclosemessage']));
		}

		$query = DB::query("SELECT * FROM #__common_setting WHERE skey IN ('bbrules', 'bbrulesforce', 'bbrulestxt', 'welcomemsg', 'welcomemsgtitle', 'welcomemsgtxt')");
		while ($setting = DB::fetch($query)) {
			$$setting['skey'] = $setting['svalue'];
		}

		$groupinfo = array();
		//新注册用户组ID
		$groupinfo['groupid'] = 10;

		$fromuid = !empty($_G['cookie']['promotion']) ? intval($_G['cookie']['promotion']) : 0;

		$username = isset($_G['gp_username']) ? $_G['gp_username'] : '';

		$bbrulehash = $bbrules ? substr(md5(FORMHASH), 0, 8) : '';
		$auth = $_G['gp_auth'];

		if (!submitcheck('regsubmit', 0)) {
			$_G['referer'] = isset($_G['referer']) ? dhtmlspecialchars($_G['referer']) : dreferer();

			$fromuser = !empty($fromuser) ? dhtmlspecialchars($fromuser) : '';
			if ($fromuid) {
				$query = DB::query("SELECT username FROM #__common_member WHERE uid='$fromuid'");
				if (DB::num_rows($query)) {
					$fromuser = dhtmlspecialchars(DB::result($query, 0));
				} else {
					dsetcookie('promotion');
				}
			}

			$bbrulestxt = nl2br("\n$bbrulestxt\n\n");

			$username = dhtmlspecialchars($username);
			$navtitle = $_G['setting']['reglinkname'];
			include template('member/register');
		} else {
			if ($bbrules && $bbrulehash != $_POST['agreebbrule']) {
				showmessage('You must agree to the Terms of Service before registration!');
			}
			$usernamelen = strlen($username);
			if ($usernamelen < 3) {
				showmessage('Sorry, your username is less than 3 characters, please return to enter a long user name.');
			} elseif ($usernamelen > 15) {
				showmessage('Sorry, your user name more than 15 characters, please return to enter a shorter user name.');
			}
			$username = addslashes(trim(dstripslashes($username)));
			if (DB::result_first("SELECT uid FROM #__common_member WHERE username='$username'")) {
				if ($_G['inajax']) {
					showmessage('The user name is already registered');
				} else {
					showmessage('Sorry, you enter the user name "{username}" already exists, please visit the site to activate this account.', 'index.php?option=member&task=login', array('username' => $username));
				}
			}

			if ($_G['gp_password'] !== $_G['gp_password2']) {
				showmessage('The two passwords are not, please return.');
			}

			if (!$_G['gp_password'] || $_G['gp_password'] != addslashes($_G['gp_password'])) {
				showmessage('Password empty or contains illegal characters, go back to re-fill.');
			}

			$email = trim($_G['gp_email']);
			$password = $_G['gp_password'];

			$censorexp = '/^(' . str_replace(array('\\*', "\r\n", ' '), array('.*', '|', ''), preg_quote(($_G['setting']['censoruser'] = trim($_G['setting']['censoruser'])), '/')) . ')$/i';

			if ($_G['setting']['censoruser'] && @preg_match($censorexp, $username)) {
				showmessage('Shielded by the system user name contains characters');
			}

			$ctrlip = $_G['clientip'];
			if ($_G['setting']['regctrl']) {
				$query = DB::query("SELECT ip FROM #__common_regip WHERE ip LIKE '$ctrlip' AND count='-1' AND dateline>$_G[timestamp]-'" . $_G['setting']['regctrl'] . "'*3600 LIMIT 1");
				if (DB::num_rows($query)) {
					showmessage('IP address can not be registered within {Regctrl} hours', NULL, array('regctrl' => $_G['setting']['regctrl']));
				}
			}

			$secques = $questionid > 0 ? random(8) : '';

			$uid = addmember($username, $password, $email, $questionid, $answer);

			if ($uid <= 0) {
				if ($uid == -1) {
					showmessage('User name contains sensitive characters');
				} elseif ($uid == -2) {
					showmessage('Shielded by the system user name contains characters');
				} elseif ($uid == -3) {
					showmessage('The user name is already registered');
				} elseif ($uid == -4) {
					showmessage('The email address is invalid');
				} elseif ($uid == -5) {
					showmessage('Email contains the mailbox name not be used');
				} elseif ($uid == -6) {
					showmessage('The Email address is already registered');
				} else {
					showmessage('Undefined action, please return.', NULL);
				}
			}


			if ($_G['setting']['regfloodctrl']) {
				if ($regattempts = DB::result_first("SELECT count FROM #__common_regip WHERE ip='$_G[clientip]' AND count>'0' AND dateline>'$_G[timestamp]'-86400")) {
					if ($regattempts >= $_G['setting']['regfloodctrl']) {
						showmessage('The same IP address can only be registered within 24 hours, {regfloodctrl} times', NULL, array('regfloodctrl' => $_G['setting']['regfloodctrl']));
					} else {
						DB::query("UPDATE #__common_regip SET count=count+1 WHERE ip='$_G[clientip]' AND count>'0'");
					}
				} else {
					DB::query("INSERT INTO #__common_regip (ip, count, dateline)
						VALUES ('$_G[clientip]', '1', '$_G[timestamp]')");
				}
			}

			$password = md5($password);


			$totalmembers = DB::result_first("SELECT COUNT(*) FROM #__common_member");

			if ($_G['setting']['regctrl'] || $_G['setting']['regfloodctrl']) {
				DB::query("DELETE FROM #__common_regip WHERE dateline<='$_G[timestamp]'-" . ($_G['setting']['regctrl'] > 72 ? $_G['setting']['regctrl'] : 72) . "*3600", 'UNBUFFERED');
				if ($_G['setting']['regctrl']) {
					DB::query("INSERT INTO #__common_regip (ip, count, dateline)
						VALUES ('$_G[clientip]', '-1', '$_G[timestamp]')");
				}
			}

			$_G['uid'] = $uid;
			$_G['username'] = $username;
			$_G['member']['username'] = dstripslashes($_G['username']);
			$_G['member']['password'] = $password;
			$_G['groupid'] = $groupinfo['groupid'];
			//设置登录状态
			$_CORE = & cmsCore::instance();
			$_CORE->session->set('uid', $uid);
			$_CORE->session->set('username', $username);

			dsetcookie('auth', authcode("$password\t$uid", 'ENCODE'), 2592000, 1, true);

			if ($welcomemsg && !empty($welcomemsgtxt)) {
				$welcomtitle = !empty($_G['setting']['welcomemsgtitle']) ? $_G['setting']['welcomemsgtitle'] : "Welcome to " . $_G['setting']['sitename'] . "!";
				$welcomtitle = addslashes(replacesitevar($welcomtitle));
				$welcomemsgtxt = addslashes(replacesitevar($welcomemsgtxt));
				if ($welcomemsg == 2) {
					if(!sendmail($email, $welcomtitle, $welcomemsgtxt)) {
						runlog('sendmail', "$email sendmail failed.");
					}
				}
			}

			if ($fromuid) {
				updatecreditbyaction('promotion_register', $fromuid);
				dsetcookie('promotion', '');
			}

			dsetcookie('invite_auth', '');

			loadcache('setting', true);
			save_syscache('setting', $_G['setting']);

			if (!empty($_G['inajax'])) {
				$mrefreshtime = intval($_G['setting']['msgforward']) * 1000;
				$message = 1;
				include template('member/register');
			}
			showmessage('Thank you for registration!', dreferer());
		}
	}

	/**
	 * 清除COOKIE
	 *
	 * @global array $_G
	 * @global array $_COOKIE
	 * @global array $formhash
	 */
	function onClearCookies() {
		global $_G, $_COOKIE, $formhash;
		define('CURMODULE', 'clearcookies');
		if (is_array($_COOKIE) && (empty($_G['uid']) || ($_G['uid'] && $formhash == formhash()))) {
			foreach ($_G['cookie'] as $key => $val) {
				dsetcookie($key, '', -1, 0);
			}
			foreach ($_COOKIE as $key => $val) {
				setcookie($key, '', -1, $_G['config']['cookie']['cookiepath'], '');
			}
		}
		showmessage('Log traces have been removed!', 'index.php', array(), $_G['inajax'] ? array('msgtype' => 3, 'showmsg' => true) : array());
	}

	/**
	 * 登录
	 * @global array $_G
	 */
	function onLogin() {
		global $_G;
		define('CURMODULE', 'login');
		if ($_G['uid']) {
			$param = array('username' => $_G['member']['username'], 'uid' => $_G['member']['uid']);
			$fromurl = dreferer();
			//如果没有来路网址，或者来路网址是登陆的话，则自动跳转到首页
			if(strpos($fromurl, 'task=login') || empty($fromurl)) $fromurl = 'index.php';
			showmessage('Welcome back, {username}. Log in now will be transferred to the former page.', $fromurl, $param, array('showdialog' => 1, 'locationtime' => true));
		}
		if (!submitcheck('loginsubmit', 1)) {
			$_G['referer'] = dreferer();
			$thetimenow = '(GMT ' . ($_G['setting']['timeoffset'] > 0 ? '+' : '') . $_G['setting']['timeoffset'] . ') ' .
					dgmdate(TIMESTAMP, 'u') .
					$cookietimecheck = !empty($_G['cookie']['cookietime']) ? 'checked="checked"' : '';
			$navtitle = lang('core', 'User Login');
			include template('member/login');
		} else {
			if (!($_G['member_loginperm'] = logincheck())) {
				showmessage('Wrong password too many times, please log in again after 15 minutes!');
			}
			if ($_G['gp_fastloginfield']) {
				$_G['gp_loginfield'] = $_G['gp_fastloginfield'];
			}
			$_G['uid'] = $_G['member']['uid'] = 0;
			$_G['username'] = $_G['member']['username'] = $_G['member']['password'] = '';
			$result = userlogin($_G['gp_username'], $_G['gp_password'], $_G['gp_questionid'], $_G['gp_answer'], $_G['setting']['autoidselect'] ? 'auto' : $_G['gp_loginfield']);
			if ($result['status'] > 0) {
				setloginstatus($result['member'], $_G['gp_cookietime'] ? 2592000 : 0);
				DB::query("UPDATE #__common_member SET lastip='" . $_G['clientip'] . "', lastvisit='" . time() . "' WHERE uid='$_G[uid]'");

				updatecreditbyaction('daylogin', $_G['uid']);
				checkusergroup($_G['uid']);
				if (!empty($_G['inajax']) && empty($_G['gp_quickforward'])) {
					$mrefreshtime = intval($_G['setting']['msgforward']) * 1000;
					loadcache('usergroups');
					$usergroups = addslashes($_G['cache']['usergroups'][$_G['groupid']]['grouptitle']);
					$message = 1;
					include template('member/login');
				} else {
					$param = array('username' => $_G['member']['username'], 'uid' => $_G['member']['uid']);
					if ($_G['groupid'] == 8) {
						showmessage('Welcome back, {username}. Your account is inactive, it will be transferred to the control panel.', 'index.php', $param);
					} else {
						showmessage('Welcome back, {username}. Log in now will be transferred to the former page.', dreferer(), $param);
					}
				}
			} elseif ($result['status'] == -1) {
				$auth = authcode($result['ucresult']['username'] . "\t" . FORMHASH, 'ENCODE');
				$location = 'index.php?option=member&task=' . $_G['setting']['regname'] . '&action=activation&auth=' . rawurlencode($auth);
				if ($_G['inajax'] && empty($_G['gp_quickforward'])) {
					$message = 2;
					include template('member/login');
				} else {
					showmessage('你的帐号未在本站点激活，现在将转入帐号激活页面。', $location);
				}
			} else {
				$password = preg_replace("/^(.{" . round(strlen($_G['gp_password']) / 4) . "})(.+?)(.{" . round(strlen($_G['gp_password']) / 6) . "})$/s", "\\1***\\3", $_G['gp_password']);
				$errorlog = dhtmlspecialchars(
								TIMESTAMP . "\t" .
								($result['ucresult']['username'] ? $result['ucresult']['username'] : dstripslashes($_G['gp_username'])) . "\t" .
								$password . "\t" .
								"Ques #" . intval($_G['gp_questionid']) . "\t" .
								$_G['clientip']);
				writelog('illegallog', $errorlog);
				loginfailed($_G['member_loginperm']);
				$fmsg = $result['ucresult']['uid'] == '-3' ? (empty($_G['gp_questionid']) || $answer == '' ? 'Please fill in the security question and the correct answer!' : 'Select security question wrong, please re-fill!') : 'Login failed, you can try {loginperm} times';
				showmessage($fmsg, '', array('loginperm' => $_G['member_loginperm']));
			}
		}
	}

	/**
	 * 注销
	 *
	 * @global array $_G
	 */
	function onLogout() {
		global $_G;
		define('CURMODULE', 'logout');
		if ($_G['gp_formhash'] != $_G['formhash']) {
			showmessage('You have to exit the site, and now as a visitor, will be transferred to the page before exiting. <br /> <a href="index.php?option=member&task=clearcookies&formhash={formhash}"> [remove traces] </ a>', dreferer(), array('formhash' => FORMHASH));
		}
		clearcookies();
		$_G['groupid'] = $_G['member']['groupid'] = 7;
		$_G['uid'] = $_G['member']['uid'] = 0;
		$_G['username'] = $_G['member']['username'] = $_G['member']['password'] = '';
		$_G['setting']['styleid'] = $_G['setting']['styleid'];
		showmessage('You have to exit the site, and now as a visitor, will be transferred to the page before exiting. <br /> <a href="index.php?option=member&task=clearcookies&formhash={formhash}"> [remove traces] </ a>', dreferer(), array('formhash' => FORMHASH));
	}

}

/**
 * 清除COOKIE信息
 *
 * @global array $_G
 */
function clearcookies() {
	global $_G;
	foreach (array('sid', 'auth') as $k) {
		dsetcookie($k);
	}
	$_G['uid'] = $_G['adminid'] = 0;
	$_G['username'] = $_G['member']['password'] = '';
}
